#include "Tcpconnection.h"
#include "Channel.h"

namespace liu
{

	TcpConnection::TcpConnection(Eventloop* pLoop, int sockfd)
		:m_pLoop(pLoop),
		m_sockfd(sockfd),
		m_pChannel(make_unique<Channel>(m_pLoop, m_sockfd))
	{
		m_pChannel->m_readCallback = bind(&TcpConnection::handleRead, this);
		m_writeCallback = bind(&TcpConnection::handleWrite, this);
	}

	TcpConnection::~TcpConnection()
	{
		cout << debug_time() << "call TcpConnection::~TcpConnection()" << endl;
		::close(m_sockfd);
	}

	void TcpConnection::handleRead()
	{
		RUN_TRACE;
		char buf[1024] = { 0, };
		ssize_t n = ::read(m_sockfd, buf, sizeof buf);

		cout << debug_time() << "TcpConnection::handleRead() read n:[" << n << "] bytes." << endl;

		if (n > 0)
		{
			cout << debug_time() << "TcpConnection::handleRead() read content:[" << buf << "]." << endl;
		}
	}

	void TcpConnection::handleWrite()
	{

	}

	void TcpConnection::send(const string& msg)
	{
		int n = ::write(m_sockfd, msg.c_str(), msg.length());
	}

	void TcpConnection::connectEstablished()
	{
		RUN_TRACE;
		m_pChannel->m_events = EPOLLIN | EPOLLPRI;
		m_pChannel->update();
		m_connCallback(shared_from_this());
		cout << debug_time() << "TcpConnection::connectEstablished add fd:[" << m_pChannel->m_fd
			<< "] to epoll event." << endl;
	}

}